<template>
  <div class="price-selector">
    <el-popover
      placement="bottom-start"
      title="选择价格区间"
      :width="300"
      trigger="hover"
      v-model:visible="popoverVisible"
    >
      <div class="price-range">
        <el-input
          v-model="minPrice"
          placeholder="¥最低价"
          size="small"
          style="width: 120px"
        />
        <span>~</span>
        <el-input
          v-model="maxPrice"
          placeholder="¥最高价"
          size="small"
          style="width: 120px"
        />
      </div>
      <div class="buttons">
        <el-button size="small" @click="reset">重置</el-button>
        <el-button type="primary" size="small" @click="apply">应用</el-button>
      </div>
      <template #reference>
        <el-button class="m-2">{{ buttonText }}</el-button>
      </template>
    </el-popover>
    <el-button v-if="showReset" @click="externalReset" class="m-2">重置</el-button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const minPrice = ref('')
const maxPrice = ref('')
const originalText = '价格区间'
const popoverVisible = ref(false)
const showReset = ref(false)


const buttonText = computed(() => {
  if (minPrice.value || maxPrice.value) {
    const min = minPrice.value || '0'
    const max = maxPrice.value || '∞'
    return `¥${min} ~ ¥${max}`
  }
  return originalText
})

const reset = () => {
  minPrice.value = ''
  maxPrice.value = ''
  showReset.value = false
}
const emits=defineEmits(['update:price'])
const transitPrice=()=>{
    emits('update:price',{minPrice,maxPrice})
}
const apply = () => {
  const min = minPrice.value || '0'
  console.dir(min)
  const max = maxPrice.value|| `${parseFloat(min) + 1000000000}`
  console.dir(max)
  console.log(`Applying price range: ¥${min} - ¥${max}`)
  popoverVisible.value = false
  showReset.value = true
  emits('update:price',{min,max})
}

const externalReset = () => {
  reset()
  const min = minPrice.value || '0'
  console.dir(min)
  const max = maxPrice.value|| `${parseFloat(min) + 1000000000}`
  console.dir(max)
  emits('update:price',{min,max})
}
</script>

<style scoped>
.price-range {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.buttons {
  display: flex;
  justify-content: space-between;
}

.el-button + .el-button {
  margin-left: 8px;
}

.price-selector {
  display: flex;
  align-items: center;
  margin-left: 5%;
}
</style>